package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询数据库中用户信息
     * @param username
     * @return
     */
    public User getByName(String username) {
        // 从数据库中查询用户
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        // 查询用户的角色
        List<Role> roles = userMapper.loadRolesByUserId(user.getId());
        Set<Role> set = new HashSet<>(roles);
        user.setRoles(set);
        return user;
    }
}
